import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/use_record/widgets/show_detail.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

enum TabType {
  date,
  month,
  year
}

class TabLayout extends StatefulWidget {
  final TabType type;
  final int id;
  const TabLayout({super.key, this.type = TabType.date, required this.id});

  @override
  State<StatefulWidget> createState() => _TabLayoutState();

}

enum DateOperationType {
  increase,
  decrease
}

class _TabLayoutState extends State<TabLayout> {

  late String _currentDate;
  late String _format;
  late List _list;
  final Map _dateOperationMap = {
    DateOperationType.increase: 1,
    DateOperationType.decrease: -1,
  };

  bool showArrowRight() {
    String curDate = DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: _format);
    return curDate == _currentDate;
  }


  void dateOperation(DateOperationType type) {
    setState(() {
      String date;

      if (widget.type == TabType.month) {
        date = "$_currentDate-01";
        DateTime duration = DateTime(DateTime.parse(date).year, DateTime.parse(date).month + (type == DateOperationType.increase ? 1 : -1), DateTime.parse(date).day);
        _currentDate = DateTools.formatTime(duration.millisecondsSinceEpoch, format: _format);
      } else if (widget.type == TabType.year) {
        date = "$_currentDate-01-01";
        DateTime duration = DateTime(DateTime.parse(date).year + (type == DateOperationType.increase ? 1 : -1), DateTime.parse(date).month, DateTime.parse(date).day);
        _currentDate = DateTools.formatTime(duration.millisecondsSinceEpoch, format: _format);
      } else {
        date = _currentDate;
        _currentDate = DateTools.formatTime(DateTime.parse(date).add(Duration(days: _dateOperationMap[type])).millisecondsSinceEpoch, format: _format);
      }
    });
    
    _useRecord();
  }

  Future<void> _useRecord() async {
    String startDate, endDate;
    String dateType;
    switch (widget.type) {
      case TabType.date:
        startDate = _currentDate;
        endDate = _currentDate;
        dateType = "day";
        break;
      case TabType.month:
        startDate = "$_currentDate-01";
        DateTime firstDay = DateTime.parse("$_currentDate-01");
        DateTime lastDay = DateTime(firstDay.year, firstDay.month + 1, 0);
        endDate = DateTools.formatTime(lastDay.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
        dateType = "month";
        break;
      case TabType.year:
        startDate = "$_currentDate-01-01";
        endDate = "$_currentDate-12-31";
        dateType = "year";
        break;
    }

    Map<String, dynamic> params = {
      "electricityMeterId": widget.id,
      "startDate": startDate,
      "endDate": endDate,
      "dateType": dateType
    };
    
    EasyLoading.show();
    try {
      Map resData = await electricityMeterApi.useRecord(params);
      setState(() {
        _list = resData["rows"] ?? [];
      });
    } catch (e) {
      print("Error fetching records: $e");
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> _refresh() async {
    await _useRecord();
  }

  @override
  void initState() {
    setState(() {
      _list = [];
      switch (widget.type) {
        case TabType.date:
          _format = "{y}-{m}-{d}";
          break;
        case TabType.month:
          _format = "{y}-{m}";
          break;
        case TabType.year:
          _format = "{y}";
          break;
        default:
          _format = "{y}-{m}-{d}";
          break;
      }
      _currentDate = DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: _format);
    });
    _useRecord();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh,
      child: Stack(
        children: [
          ListView(
            padding: const EdgeInsets.only(top: 50),
            children: [
              if (_list.isNotEmpty) Column(
                children: List.generate(_list.length * 2 - 1, (index) {
                  if (index.isOdd) {
                    return const SolidDivider(padding: EdgeInsets.only(left: ThemeVars.paddingPage),);
                  }

                  Map item = _list[index ~/ 2];
                  return GestureDetector(
                    onTap: () {
                      showDetail(context: context, record: item);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 12),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(item["groupDate"]),
                          Text("${item["kwh"]}度")
                        ],
                      ),
                    ),
                  );
                }),
              ) else EmptyData()
            ],
          ),
          Container(
            height: 50,
            width: MediaQuery.of(context).size.width,
            decoration: const BoxDecoration(
              color: ThemeVars.colorBackground,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButton(
                  icon: const Icon(Icons.arrow_left, size: 30,),
                  onPressed: () {
                    dateOperation(DateOperationType.decrease);
                  },
                ),
                SizedBox(
                  width: 100,
                  child: Text(_currentDate, textAlign: TextAlign.center, style: const TextStyle(fontSize: 16),),
                ),
                showArrowRight()
                    ? const SizedBox(width: 46,)
                    : IconButton(
                  icon: const Icon(Icons.arrow_right, size: 30,),
                  onPressed: () {
                    dateOperation(DateOperationType.increase);
                  },
                ),
                // Icon(Icons.arrow_right, size: 30,),
                // SizedBox(width: 30,)
              ],
            ),
          )
        ],
      ),
    );
  }

}